package com.ccl.iot.object;

import com.ccl.iot.IOTNetAPI;

public class IOTInfoHeader {
	/*
	 * 	Static functions
	 */
	public static String Encode(String aPrefix, long aID, String aName){
		if (aName != null && aName.length() > 0){
			if (aPrefix != null){
				return aPrefix + IOTNetAPI.GetStringID(aID) + ":" + aName;
			}else{
				return IOTNetAPI.GetStringID(aID) + ":" + aName;
			}
		}else{
			if (aPrefix != null){
				return aPrefix + IOTNetAPI.GetStringID(aID);
			}else{
				return IOTNetAPI.GetStringID(aID);
			}
		}
	}
	
	public static String Encode(String aID, String aName){
		if (aName != null && aName.length() > 0){
			return aID + ":" + aName;
		}else{
			return aID;
		}
	}
	
	public static IOTInfoHeader Decode(String aPrefix, String aNameLabel){
		if (aNameLabel != null){
			if (aPrefix == null || aNameLabel.startsWith(aPrefix)){
				String tLabel[] = aNameLabel.split(":");
				
				if (tLabel != null && tLabel.length > 0){
					IOTInfoHeader tHeader = null;
					
					if (tLabel.length == 1){
						tHeader = new IOTInfoHeader(aPrefix, new String(tLabel[0]), "");
					}else if (tLabel.length >= 2){
						tHeader = new IOTInfoHeader(aPrefix, new String(tLabel[0]), new String(tLabel[1]));
					}
					
					if (tHeader != null && tHeader.isValid()){
						return tHeader;
					}
				}
			}
		}
		
		return null;
	}
	
	/*
	 * 	Non-static functions
	 */
	private String iPrefix = null;
	private String iID;
	private long iLongID = 0;
	private String iName = null;
	
	IOTInfoHeader(String aPrefix, String aID, String aName){
		iPrefix = aPrefix;
		iID = aID;
		
		iName = aName;
	}
	
	public String getPrefix(){
		return iPrefix;
	}
	
	public String getID(){
		return iID;
	}
	
	public long getLongID(){
		if (iLongID == 0){
			if (iPrefix != null && iID != null){
				iLongID = IOTNetAPI.GetLongID(iID.substring(iPrefix.length()));
			}
		}
		
		return iLongID;
	}
	
	public String getName(){
		return iName;
	}
	
	public boolean isValid(){
		return iID != null && iName != null;
	}

	@Override
	public String toString() {
		if (iName == null || iName.length() == 0){
			return String.valueOf(iID);
		}else{
			return iID + ":" + iName;
		}
	}
}
